package com.zy.design.pattern.observer.guava;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.zy.design.pattern.observer.syn.LoginMessage;

import java.util.concurrent.Executors;

/**
 * @author zhaoyi
 * @date 2021/4/25 14:55
 * 基于 Google Guava EventBus(事件总线)
 * 不需要定义
 */
public class LoginObservableByEventBus {

    private EventBus eventBus;

    public LoginObservableByEventBus() {
        //eventBus = new EventBus();
        eventBus = new AsyncEventBus(Executors.newSingleThreadExecutor());
    }

    public void login(String username, String password) {
        if (username == null || username.isEmpty()) {
            System.out.println("******登录失败****");
            return;
        }

        System.out.println("~~~~登录成功通知观察者~~~~~");
        //登录失败抛异常
        LoginMessage message = new LoginMessage("发积分", username.hashCode());
        eventBus.post(message);
        eventBus.post(username);

    }


    public void add(Object observer) {
        eventBus.register(observer);
    }


    public void remove(Object observer) {
        eventBus.unregister(observer);
    }


}
